package com.app;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class SvLifecycle extends SurfaceView implements Callback, Runnable{
	private SurfaceHolder	sfh;
	private Thread			th;
	private Canvas			canvas;
	private Paint			paint;
	private int				ScreenW, ScreenH;
	public void initView() {
		Log.e("View", "构造");
		sfh = this.getHolder();
		sfh.addCallback(this);//监听SurfaceView的改变

		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setColor(Color.RED);
		paint.setTextSize(20);
		
		this.setKeepScreenOn(true);//保持屏幕常亮
		this.setFocusable(true);//获得焦点
		this.setFocusableInTouchMode(true);
	}

	public SvLifecycle(Context context) {
		super(context);
		initView();
	}

	//此构造函数，是多View显示的关键
	public SvLifecycle(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e("View", "Created");
		isRun = true;
		th = new Thread(this);
		th.start();
		System.out.println(ScreenW + "\t" + ScreenH);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		Log.e("View", "Changed");
		// SurfaceView被创建后才能获取
		// 构造完不等于View被创建
		// View获得显示权才会创建
		ScreenW = this.getWidth();
		ScreenH = this.getHeight();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.e("View", "Destroyed");
		isRun = false;
	}

	//控制关闭多余线程，Home时
	private boolean	isRun	= true;

	public void run() {
		while (isRun) {
			try {
				Mydraw();
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void Mydraw() {
		try {
			canvas = sfh.lockCanvas(); // 得到一个canvas实例 ，加锁
			if (canvas != null) {
				canvas.drawColor(Color.WHITE);// 刷屏
				canvas.drawText("永恒的", 0, 0, paint);
				canvas.drawText("Hello", 100, 100, paint);// 画文字文本
				canvas.drawText("这就是简单的一个游戏框架View1", 20, 160, paint);
			}
		} catch (Exception ex) {
		} finally {//保证 画布的提交，以及避免错误提交
			if (canvas != null)
				sfh.unlockCanvasAndPost(canvas); // 将画好的画布提交，解锁
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.i("View", "key="+keyCode);
		return super.onKeyDown(keyCode, event);
	}
	
}
